<template>
    <!-- 报名管理 -->
    <div class="scheme">
        <div class="header-box">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-row>
                    <el-form-item label="状态：">
                        <el-select v-model="formInline.status" placeholder="请选择" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="待支付" value="1"></el-option>
                            <el-option label="待预约" value="2"></el-option>
                            <el-option label="待核销" value="3"></el-option>
                            <el-option label="已核销" value="4"></el-option>
                            <el-option label="退款中" value="5"></el-option>
                            <el-option label="已取消" value="6"></el-option>
                            <el-option label="已失效" value="7"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="支付方式：">
                        <el-select v-model="formInline.pay_type" placeholder="请选择" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="微信支付" value="1"></el-option>
                            <el-option label="积分支付" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="报名ID：">
                        <el-input v-model="formInline.id" placeholder="请输入报名ID"></el-input>
                    </el-form-item>
                    <el-form-item label="订单编号：">
                        <el-input v-model="formInline.order_no" placeholder="请输入订单编号"></el-input>
                    </el-form-item>
                    <el-form-item label="课程搜索：">
                        <el-input v-model="formInline.course_name" placeholder="请输入搜索课程名称"></el-input>
                    </el-form-item>
                    <el-form-item label="所属门店:">
                        <el-select v-model="formInline.store_id" filterable placeholder="请选择门店">
                            <el-option label="全部" value=""></el-option>
                            <el-option :label="item.name" :value="item.id" v-for="item in storeList" :key="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="教练:">
                        <el-select v-model="formInline.teacher_id" filterable placeholder="请选教练">
                            <el-option label="全部" value=""></el-option>
                            <el-option :label="item.nickname" :value="item.id" v-for="item in teacherList"
                                       :key="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="课程ID搜索：">
                        <el-input v-model="formInline.course_id" placeholder="请输入搜索课程ID"></el-input>
                    </el-form-item>
                    <el-form-item label="用户手机号搜索：">
                        <el-input v-model="formInline.user_mobile" placeholder="请输入搜索用户手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="创建时间:">
                        <el-date-picker v-model="formInline.created_at" format="yyyy-MM-dd HH:mm:ss"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                        type="datetimerange" range-separator="至" start-placeholder="开始日期"
                                        end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="submitForm">搜索</el-button>
                    </el-form-item>

                </el-row>


            </el-form>
        </div>
        <div class="tables">
            <el-table border :data="tableData"
                      :summary-method="getSummaries"
                      show-summary
                      max-height="650" highlight-current-row :row-style="{height: '20px'}"
                      :header-cell-style="{background:'#e6e6e6',color:'#000000'}">
                <el-table-column prop="id" align="center" label="报名ID"></el-table-column>
                <el-table-column prop="order_no" align="center" label="订单编号" width="130px"></el-table-column>
                <el-table-column prop="course_name" align="center" label="课程名称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="week_time" align="center" label="课程时间" show-overflow-tooltip></el-table-column>
                <el-table-column prop="status" align="center" label="支付方式">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.pay_type === 1 ? 'success' : 'danger'"
                                disable-transitions>{{ scope.row.pay_type === 1 ? '微信' : '积分' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="user_mobile" align="center" label="用户手机号" width="130px"></el-table-column>
                <el-table-column prop="price" align="center" label="单价"></el-table-column>
                <el-table-column prop="book_num" align="center" label="预订节数"></el-table-column>
                <el-table-column prop="book_money" align="center" label="总金额"></el-table-column>
                <el-table-column prop="used_num" align="center" label="核销节数"></el-table-column>
                <el-table-column prop="date_num" align="center" label="约课节数"></el-table-column>
                <!--                <el-table-column prop="expire_num" align="center" label="过期节数"></el-table-column>-->
                <el-table-column prop="back_num" align="center" label="退订节数"></el-table-column>
                <el-table-column prop="left_num" align="center" label="剩余节数"></el-table-column>
                <el-table-column prop="status_name" align="center" label="状态"></el-table-column>
                <el-table-column prop="created_at" align="center" label="创建日期" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button size="mini" type="success" plain v-if="scope.row.back_num>0"
                                   @click="goToRefund(scope.row.order_no)">
                            退款详情
                        </el-button>
                        <el-button size="mini" type="warning" plain
                                   v-if="scope.row.status>1 && scope.row.status<7 && scope.row.date_num>0"
                                   @click=goToInfo(scope.row.order_no)>预约详情
                        </el-button>
                        <el-button v-if="scope.row.status>1 && scope.row.status<7 && scope.row.left_num>0" size="mini"
                                   type="danger" plain
                                   @click=goToApply(scope.row)>申请退款
                        </el-button>
                        <!--                        <el-button v-if="scope.row.status>1 && scope.row.status<7 && scope.row.date_num>0" size="mini" type="danger" plain-->
                        <!--                                   @click=goToUse(scope.row)>核销-->
                        <!--                        </el-button>-->
                        <el-button v-if="scope.row.status==1" type="danger"
                                   @click=goToInvalid(scope.row)>作废
                        </el-button>
                        <el-button
                            v-if="scope.row.status>1 && scope.row.status<6 && scope.row.used_num==0 && scope.row.back_num==0"
                            type="danger"
                            @click=goToCancel(scope.row)>取消
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :current-page.sync="page" :page-sizes="[15, 20, 50, 100]" :page-size="limit"
                               layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>
        <!--申请退款弹窗 -->
        <el-dialog title="退款申请单" :visible.sync="dialogApply">
            <el-form :model="form" :rules="rules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="支付方式:" prop="is_wx_pay" v-if="form.is_wx_pay">
                            微信支付
                        </el-form-item>
                        <el-form-item label="支付方式:" prop="is_wx_pay" v-else>
                            积分支付
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="可退款节数:" prop="left_num">
                            {{ form.left_num }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="退款节数:" prop="num">
                            <el-input v-model="form.num" style="width: 313px;" @change="handleChangeNum">
                                <template slot="append">节</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="单价:" prop="price">
                            {{ form.price }}元
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="可最大退款金额：" prop="can_back_money">
                            {{ form.can_back_money }}元
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="当前积分兑换比率" prop="point_rate">
                            {{ form.point_rate }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="可退款最大积分" prop="can_back_point">
                            {{ form.can_back_point }}积分
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="退款总金额：" prop="total_money">
                            {{ form.total_money }}元
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="退款金额" prop="back_money">
                            <el-input v-model="form.back_money" type="number" min="0" style="width: 313px;"
                                      @change="handleChangeBackMoney">
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="退款积分" prop="back_point">
                            <el-input v-model="form.back_point" type="number" min="0" style="width: 313px;"
                                      @change="handleChangeBackPoint">
                                <template slot="append">积分</template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitData">确 定</el-button>
            </div>
        </el-dialog>

        <!--销课弹窗 -->
        <el-dialog title="销课(<p style>注意此处核销是的是剩余的课时，若要核销已预约课时请到预约详情中核销</p>)" :visible.sync="dialogUse"
                   :show-close="false" :close-on-click-modal="false"
                   :close-on-press-escape="false">
            <el-form :model="useForm" :rules="use_rules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="课程名称:" prop="course_name">
                            {{ useForm.course_name }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户手机号:" prop="user_mobile">
                            {{ useForm.user_mobile }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="可核销节数:" prop="left_num">
                            {{ useForm.left_num }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="核销节数:" prop="num">
                            <el-input v-model="useForm.num" type="number"
                                      style="width: 313px;" @change="handleChangeUseNum"
                            >
                                <template slot="append">节</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="核销日期:" prop="date">
                            <el-date-picker v-model="useForm.date"
                                            type="date"
                                            placeholder="请选择核销日期"
                                            value-format="yyyy-MM-dd"
                                            format="yyyy-MM-dd"
                            >

                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="useForm.remark" style="width: 313px;"></el-input>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogUse=false">取 消</el-button>
                <el-button type="primary" @click="submitUseData">确 定</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>

import {isEmpty} from "lodash/lang";

export default {
    name: "user_course_info",
    data() {
        return {
            formInline: {
                status: "",
                pay_type: "",
                id: "",
                order_no: "",
                course_name: "",
                course_id: "",
                user_mobile: "",
                member_name: "",
                store_id: "",
                teacher_id: "",
            },
            tableData: [
                {
                    id: 1,
                    name: "社区体能课（周一）",
                    type: "体能课程",
                    image: "/",
                    time: "每星期一17:00~18:00",
                    address: "宝安区四季公园",
                    desc: "这个课程是有助于儿童健康成长",
                    status: 1,
                },
            ],
            teacherList: [],
            id: 0,
            page: 1, //默认第一页
            limit: 15, //默认一页显示10条数据
            total: 0,

            //退款表单

            dialogApply: false,
            form: {
                id: 0,
                point_rate: 1,
                left_num: 0,
                can_back_money: 0,
                can_back_point: 0,
                num: 0,
                price: 0,
                total_money: 0,
                back_money: 0,
                back_point: 0,
                is_wx_pay: false,
            },
            rules: {
                num: [{required: true, message: "请输入退款节数", trigger: "blur"}],
                back_money: [{required: true, message: "请输入退款金额", trigger: "blur"}],
                back_point: [{required: true, message: "请输入退款积分", trigger: "blur"}],
            },
            useForm: {
                course_name: '',
                user_mobile: '',
                left_num: 0,
                num: '',
                date: '',
                remark: '',
            },
            use_rules: {
                num: [{required: true, message: "请输入核销节数", trigger: "blur"}],
                date: [{required: true, message: "请选择核销课程日期", trigger: "blur"}],
            },
            dialogUse: false,
            storeList: [],
            dataTotal: {
                title:'总计',
                book_num: 0,
                book_money: 0,
                used_num: 0,
                date_num: 0,
                back_num: 0,
                left_num: 0,

            },

        };
    },
    created() {
        this.formInline.course_id = this.$route.query.course_id;
        this.formInline.order_no = this.$route.query.order_no;
        this.getUserCourseList();
        this.getConfigList();
        this.getStoreList();
        this.getTeacherList();
    },
    activated() {
        this.formInline.course_id = this.$route.query.course_id;
        this.formInline.order_no = this.$route.query.order_no;
        this.getUserCourseList();
        this.getConfigList();
        this.getStoreList();
        this.getTeacherList();
    },
    methods: {
        getTeacherList() {
            let params = {
                role_id: 3,
                status: 1,
                per_page: 10000,

            }
            this.$get(this.$api.adminApi, params).then((res) => {
                if (res.code == 200) {
                    this.teacherList = res.data.data;
                } else {
                    return this.$message.error(res.msg);
                }
            });

        },
        getStoreList() {
            let params = {
                status: 1,
                per_page: 10000,

            }
            this.$get(this.$api.storeApi, params).then((res) => {
                if (res.code == 200) {
                    this.storeList = res.data.data;
                } else {
                    return this.$message.error(res.msg);
                }
            });

        },
        getSummaries(param) {
            const sums = [];
            sums[0] = this.dataTotal.title;
            sums[7] = this.dataTotal.book_num;
            sums[8] = this.dataTotal.book_money;
            sums[9] = this.dataTotal.used_num;
            sums[10] = this.dataTotal.date_num;
            sums[11] = this.dataTotal.back_num;
            sums[12] = this.dataTotal.left_num;
            return sums;
        },
        getUserCourseList() {
            let params = {
                page: this.page,
                per_page: this.limit,
                status: this.formInline.status,
                pay_type: this.formInline.pay_type,
                id: this.formInline.id,
                order_no: this.formInline.order_no,
                course_name: this.formInline.course_name,
                course_id: this.formInline.course_id,
                mobile: this.formInline.user_mobile,
                store_id: this.formInline.store_id,
                teacher_id: this.formInline.teacher_id,
            };
            if (!isEmpty(this.formInline.created_at)) {
                params.start_created_at = this.formInline.created_at[0];
                params.end_created_at = this.formInline.created_at[1];
            }
            this.$get(this.$api.userCourseApi, params).then((res) => {
                if (res.code == 200) {
                    this.tableData = res.data.list.data;
                    this.total = res.data.list.total;
                    if(this.page !=1){
                        this.dataTotal = [];
                    }else{
                        this.dataTotal = res.data.total;
                        this.dataTotal.title ='总计';
                    }

                } else {
                    return this.$message.error(res.msg);
                }
            });
        },

        forEachFun(str) {
            let ids = [];
            if (str.length > 0) {
                ids = str.split(",");
                ids.forEach((item, index) => {
                    ids[index] = parseInt(ids[index])

                });
            }
            return ids;

        },

        // 确认核销
        handleUsed(row) {
            this.$confirm("此操作将核销此节课, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$put(this.$api.userCourseApi + '/' + row.id).then((res) => {
                        if (res.code == 200) {
                            this.getUserCourseList();
                            return this.$message.success("已核销！");
                        } else {
                            return this.$message.error(res.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消",
                    });
                });
        },
        // 拒绝退款
        handleRefuse(row) {
            this.$confirm("此操作将拒绝此次退款, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$post(this.$api.userCourseRefundRefuseApi, {id: row.id}).then((res) => {
                        if (res.code == 200) {
                            this.getUserCourseList();
                            return this.$message.success("已拒绝！");
                        } else {
                            return this.$message.error(res.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消",
                    });
                });
        },
        // 分页
        handleSizeChange(size) {
            this.limit = size;
            this.getUserCourseList();
        },
        handleCurrentChange(index) {
            this.page = index;
            this.getUserCourseList();
        },


        // 点击查询按钮
        submitForm() {
            this.getUserCourseList();
        },

        // 点击跳转至退款页面
        goToRefund(id) {
            this.$router.push({path: '/refund', query: {order_no: id}})
        },
        // 点击跳转至约课详情页面
        goToInfo(id) {
            this.$router.push({path: '/info', query: {order_no: id}})
        },
        goToApply(row) {
            console.log('row', row)
            console.log('point_rate', this.form.point_rate)

            this.dialogApply = true;
            this.form.id = row.id;
            this.form.price = row.price;
            this.form.left_num = row.left_num;
            this.form.num = 0;
            this.form.back_money = 0;
            this.form.back_point = 0;


            this.form.can_back_money = (row.price * 100 * row.left_num) / 100;
            console.log(row.price,)
            this.form.can_back_point = Math.floor((row.price * 100 * row.left_num) * this.form.point_rate / 100);
            this.form.total_money = 0;
            this.$get(this.$api.userCoursePayApi, {user_course_id: row.id}).then((res) => {
                if (res.code == 200) {
                    if (res.data.pay_money != 0) {
                        this.form.is_wx_pay = true;//微信支付
                    } else {
                        this.form.is_wx_pay = false;
                    }
                    if (!this.form.is_wx_pay) {
                        this.form.can_back_money = 0;
                    } else {
                        this.form.can_back_point = 0;

                    }

                } else {
                    return this.$message.error(res.msg);
                }
            });

        },
        getConfigList() {
            this.$get(this.$api.configApi, {name: 'point_rate'}).then((res) => {
                if (res.code == 200) {
                    this.form.point_rate = res.data;

                } else {
                    return this.$message.error(res.msg);
                }
            });

        },
        handleChangeNum() {
            this.form.total_money = this.form.price * 100 * this.form.num / 100;
            if (this.form.num > this.form.left_num) {
                return this.$message.error('退款节数能大于可退款节数' + this.form.left_num + '节');
            }
            if (this.form.is_wx_pay) {
                this.form.back_money = this.form.num * (this.form.price * 100) / 100;
                this.form.back_point = 0;
            } else {
                this.form.back_money = 0;
                this.form.back_point = this.form.num * (this.form.price * 100) * this.form.point_rate / 100;
            }

        },
        handleChangeBackMoney() {
            if (this.form.num == 0) {
                return this.$message.error('请先填写退款节数');
            }
            if (this.form.back_money > this.form.can_back_money) {
                return this.$message.error('退款金额不能大于' + this.form.can_back_money + '元');
            }
            this.form.back_point = (this.form.num * this.form.price - this.form.back_money) * this.form.point_rate;
        },
        handleChangeBackPoint() {
            if (this.form.num == 0) {
                return this.$message.error('请先填写退款节数');
            }
            if (this.form.back_point > this.form.can_back_point) {
                return this.$message.error('退款积分不能大于' + this.form.can_back_point);
            }
            this.form.back_money = this.form.num * this.form.price - this.form.back_point / this.form.point_rate;
        },

        cancel() {
            this.dialogApply = false;
        },
        submitData() {
            if (this.form.num == "" || this.form.num > this.form.left_num) {
                return this.$message.error('请填写正确的退款节数');
            }
            if (this.form.back_money === "" || this.form.back_money > this.form.can_back_money) {
                return this.$message.error('请填写正确的退款金额');
            }
            if (this.form.back_point === "" || this.form.back_point > this.form.can_back_point) {
                console.log(this.form.back_point)
                return this.$message.error('请填写正确的退款积分');
            }
            if (this.form.price * 100 * this.form.num / 100 != (this.form.back_money + this.form.back_point / this.form.point_rate)) {
                return this.$message.error('请填写正确的退款金额和积分');

            }
            let params = {
                id: this.form.id,
                num: this.form.num,
                back_money: this.form.back_money,
                back_point: this.form.back_point,

            }
            this.$post(this.$api.userCourseRefundApi, params).then((res) => {
                if (res.code == 200) {
                    this.dialogApply = false;
                    this.getUserCourseList();
                    return this.$message.success("申请成功，请静待审核！");
                } else {
                    return this.$message.error(res.msg);
                }
            });

        },
        //核销
        goToUse(row) {
            this.dialogUse = false;
            this.useForm.id = row.id;
            this.useForm.left_num = row.left_num;
            this.useForm.course_name = row.left_num;
            this.useForm.user_mobile = row.user_mobile;
            this.useForm.course_name = row.course_name;
        },
        handleChangeUseNum() {
            if (this.useForm.num > this.useForm.left_num || this.useForm.num < 0) {
                return this.$message.error('请填写正确核销数!');
            }
        },
        //取消
        goToInvalid(row) {
            this.$confirm("此操作将此次报名作废, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$post(this.$api.invalidUserCourseApi, {id: row.id}).then((res) => {
                        if (res.code == 200) {
                            this.getUserCourseList();
                            return this.$message.success(res.msg);
                        } else {
                            return this.$message.error(res.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消",
                    });
                });

        },
        //取消
        goToCancel(row) {
            this.$confirm("此操作将取消此次报名, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$post(this.$api.cancelUserCourseApi, {id: row.id}).then((res) => {
                        if (res.code == 200) {
                            this.getUserCourseList();
                            return this.$message.success(res.msg);
                        } else {
                            return this.$message.error(res.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消",
                    });
                });

        },
        submitUseData() {
            console.log(this.useForm.date)
            if (isEmpty(this.useForm.num)) {
                return this.$message.error('请填写核销节数');
            }
            if (isEmpty(this.useForm.date)) {
                return this.$message.error('请选择核销日期');
            }
            let params = {
                id: this.useForm.id,
                num: this.useForm.num,
                date: this.useForm.date,
                remark: this.useForm.remark
            }
            this.$post(this.$api.useUserCourseApi, params).then((res) => {
                if (res.code == 200) {
                    this.dialogUse = false;
                    this.getUserCourseList();
                    return this.$message.success(res.msg);
                } else {
                    return this.$message.error(res.msg);
                }
            });
        }


    },
};
</script>

<style scoped>
.pagination {
    text-align: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.is-selected {
    color: #1989fa;
}
</style>
